
package com.zhu.storesmanager.provider;


import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

/**
 * 内容提供器Provider
 */
public class StoresManagerProvider extends ContentProvider {

    private static final String TAG = "StoresManagerProvider";

    private DatabaseHelper mDatabaseHelper;
    private static final String DATABASE_NAME = "stores.db"; //数据库名字
    private static final int DATABASE_VERSION = 2; //版本
    public static final String AUTHORITY = "com.zhu.storesmanager.Provider"; //AUTHORITY
    public static final String PARAMETER_NOTIFY = "notify";

    public static final String TABLE_SIGNININFO = "signininfo"; //签到数据库表
    public static final String TABLE_MODELLIST = "modellist"; //所有型号数据库表
    public static final String TABLE_REMINDS = "reminds"; //提醒消息表
    public static final String TABLE_SPECIALTASKS = "specialtasks"; //促销员特殊任务表
    public static final String TABLE_REPORTEDSALES = "reportedSales"; //所有已上报的据库表
    public static final String TABLE_SUPERVISORVISITTASK = "supervisor_visitedtask"; //督导门店拜访计划表
    public static final String TABLE_SUPERVISOR_STORESAMPLE = "supervisor_storesample"; //督导门店出样表
    public static final String TABLE_DATA_DICTIONARY = "data_dictionary"; //数据词典表
    public static final String TABLE_DATA_PROJECTS = "data_projects"; //项目数据标签
    public static final String TABLE_SUPERVISOR_STOREBOOTH = "supervisor_storebooth"; //督导门店展台表
    public static final String TABLE_SUPERVISOR_STOREPOSM = "supervisor_storeposm"; //督导门店POSM布置反馈表
    public static final String TABLE_SUPERVISOR_STORESALES = "supervisor_storesales"; //督导门店销量表
    public static final String TABLE_PROMOTERINFO = "promoter_info"; //促销员信息
    public static final String TABLE_COMPETEINFO = "compete_info"; //竞品信息
    public static final String TABLE_COMPETESELECT = "compete_selected"; //竞品选择信息
    public static final String TABLE_VISITSTATUS = "supervisor_visitstatus"; //拜访标识

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        int count = db.delete(args.table, args.where, args.args);
        if (count > 0)
            sendNotify(uri);

        return count;
    }

    @Override
    public String getType(Uri arg0) {
        SqlArguments args = new SqlArguments(arg0, null, null);
        if (TextUtils.isEmpty(args.where)) {
            return "vnd.android.cursor.dir/" + args.table;
        } else {
            return "vnd.android.cursor.item/" + args.table;
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {

        SqlArguments args = new SqlArguments(uri);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        final long rowId = db.insert(args.table, null, initialValues);
        if (rowId <= 0)
            return null;

        uri = ContentUris.withAppendedId(uri, rowId);
        sendNotify(uri);

        return uri;
    }

    private void sendNotify(Uri uri) {
        String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
        if (notify == null || "true".equals(notify)) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
    }

    @Override
    public boolean onCreate() {
        // TODO Auto-generated method stub
        mDatabaseHelper = new DatabaseHelper(getContext());
        return (mDatabaseHelper == null) ? false : true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {

        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(args.table);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
        result.setNotificationUri(getContext().getContentResolver(), uri);

        return result;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        int count = db.update(args.table, values, args.where, args.args);
        if (count > 0)
            sendNotify(uri);

        return count;
    }

    public static class DatabaseHelper extends SQLiteOpenHelper {

        private Context mContext = null;

        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            mContext = context;
        }

        /**
         * 创建数据库表
         * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
         */
        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL("Create table "
                    + TABLE_SIGNININFO + " (" +  //签到数据库表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sUserid TEXT," +            //用户ID
                    "sSiginLat TEXT," +          //签到经纬度
                    "sSiginLng TEXT," +          //签到经纬度
                    "sSiginTime INTEGER NOT NULL DEFAULT 0" +          //签到时间
                    ");");

            db.execSQL("Create table "
                    + TABLE_MODELLIST + " (" +   //型号数据库表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sModelName TEXT" +          //型号名字
                    ");");

            db.execSQL("Create table "
                    + TABLE_REMINDS + " (" +  //提醒数据库表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "iRemindMSGID TEXT," +   //提醒消息ID
                    "sRemindMSGText TEXT," +  //提醒消息内容
                    "dRemindTime INTEGER," +  //提醒时间
                    "sStoreID TEXT," +        //提醒消息的门店
                    "sEventID TEXT," +        //系统消息插入日历ID
                    "sRangeName TEXT," +        //组织架构
                    "iType INTEGER," +        //消息类型
                    "dRemindDeadline INTEGER" + //到期时间
                    ");");
            
            db.execSQL("Create table "
                    + TABLE_SPECIALTASKS + " (" +   //促销员特殊任务数据库表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sStoreID TEXT,"+//门店ID
                    "iTaskID TEXT," +          //任务ID
                    "iSaved INTEGER NOT NULL DEFAULT 0," +          //是否保存的历史数据 1是 0否
                    "sTaskDescription TEXT," +  //任务描述
                    "sTaskFeedback TEXT" +  //任务反馈
                    ");");
            
            db.execSQL("Create table "
                    + TABLE_REPORTEDSALES + " (" +   //所有已上报的据库表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sModelName TEXT," +          //型号名字
                    "iSalesNum INTEGER," +          //型号销量
                    "iSalesPrice INTEGER," +          //型号价格
                    "dReportTime INTEGER" +          //上报时间
                    ");");

            db.execSQL("Create table "
                    + TABLE_SUPERVISORVISITTASK + " (" +   //督导门店拜访计划表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sStoreID TEXT," + //门店ID
                    "sStoreName TEXT," + //门店名字
                    "iVisitId INTEGER," + //拜访任务ID
                    "dVisitData INTEGER," + //拜访任务ID
                    "sCheckinStatus TEXT," + //签入时间状态 Server 表示服务器时间 App 表示手机时间
                    "dCheckinlat INTEGER," + //签入经纬度
                    "dCheckinlng INTEGER," + //签入经纬度
                    "dCheckintime INTEGER," + //签入时间
                    "sCheckoutStatus TEXT," + //签入时间状态 Server 表示服务器时间 App 表示手机时间
                    "dCheckoutlat INTEGER," + //签出经纬度
                    "dCheckoutlng INTEGER," + //签出经纬度
                    "dCheckouttime INTEGER," + //签出时间
                    "iPutSuccess INTEGER NOT NULL DEFAULT 0," + //是否上传成功
                    "dVisited INTEGER NOT NULL DEFAULT 0" + //是否已经拜访完成
                    ");");

            db.execSQL("Create table "
                    + TABLE_SUPERVISOR_STORESAMPLE + " (" +  //督导门店出样表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sStoreID TEXT," +          //门店ID
                    "iSampleCount INTEGER NOT NULL DEFAULT 0," +          //出样数  默认值0
                    "iNoneSampleCount INTEGER NOT NULL DEFAULT 0," +          //空样数  默认值 0
                    "sThemeModels TEXT," +          //主题出样型号
                    "iTimeSelected INTEGER NOT NULL DEFAULT 1," +  //流光是否选择
                    "sTimeModels TEXT," +          //流光出样型号
                    "sOtherModels TEXT," +          //其他出样型号
                    "iSaved INTEGER NOT NULL DEFAULT 0," +          //是否保存的历史数据 1是 0否
                    "sDigitDemo TEXT" +          //数码演示
                    ");");

            db.execSQL("Create table "
                    + TABLE_DATA_DICTIONARY + " (" +  //数据词典表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sDataID TEXT," +          //数据ID
                    "sDataName TEXT," +        //数据名字
                    "iDataType INTEGER" +         //数据类型
                    ");");

            db.execSQL("Create table "
                    + TABLE_DATA_PROJECTS + " (" +  //项目数据标签
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sDataName TEXT," +        //数据名字
                    "iDataType INTEGER," +         //数据类型
                    "sItemName TEXT," +        //项名字
                    "iItemShow INTEGER," +        //是否显示
                    "iSequence INTEGER," +        //项序号
                    "iItemSave INTEGER" +       //是否保存
                    ");");

            
            db.execSQL("Create table "
                    + TABLE_SUPERVISOR_STOREBOOTH + " (" +  //督导门店展台表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sStoreID TEXT," +          //门店ID
                    "sBoothShape TEXT," +        //展台形状
                    "sBoothShapeText TEXT," +        //展台形状文本
                    "sBoothInfo TEXT," +         //展台信息
                    "sBoothInfoText TEXT," +        //文本
                    "sBoothBaditems TEXT," +         //展台破损项目
                    "sBoothBaditemsText TEXT," +        //文本
                    "iBoothBadComplete INTEGER NOT NULL DEFAULT -1," +         //破损是否完工 1是 0否 -1没选中
                    "iBoothBadDate INTEGER," +         //破损日期
                    "sBoothConnection TEXT," +         //连线是否外露
                    "sBoothConnectionText TEXT," +        //文本
                    "iSaved INTEGER NOT NULL DEFAULT 0," +          //是否保存的历史数据 1是 0否
                    "sBoothPhotoAll BLOB," +         //展台全景
                    "sBoothPhotoFront BLOB," +         //展台正面
                    "sBoothPhotoTime BLOB" +         //流光溢彩墙
                    ");");
            
            db.execSQL("Create table "
                    + TABLE_SUPERVISOR_STOREPOSM + " (" +  //督导门店POSM布置反馈表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sStoreID TEXT," +          //门店ID
                    "iPrototypeCorner INTEGER NOT NULL DEFAULT -1," + //样机角贴
                    "iPoster INTEGER NOT NULL DEFAULT -1," +          //海报及吊旗悬挂
                    "iSinglePage INTEGER NOT NULL DEFAULT -1," +      //单页
                    "iStand INTEGER NOT NULL DEFAULT -1," +           //展架及堆头
                    "sErrorInfo TEXT," +           //异常详情
                    "sBackupText1 TEXT," +           //备用1标题
                    "sBackup1 TEXT," +           //备用1
                    "sBackupText2 TEXT," +           //备用2标题
                    "iSaved INTEGER NOT NULL DEFAULT 0," +          //是否保存的历史数据 1是 0否
                    "sBackup2 TEXT" +           //备用2
                    ");");

            db.execSQL("Create table "
                    + TABLE_SUPERVISOR_STORESALES + " (" +  //督导门店销量表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sStoreID TEXT," +          //门店ID
                    "iDate INTEGER," + //销售日期
                    "iAllsellcount INTEGER," + //销售总量
                    "iAllsellmoney INTEGER," +          //销售总金额
                    "sBrands TEXT," +      //品牌销量
                    "iCollect INTEGER NOT NULL DEFAULT -1," +           //台帐收集成功
                    "iCheck INTEGER NOT NULL DEFAULT -1," +           //台帐核对无误
                    "iStock INTEGER NOT NULL DEFAULT -1," +           //门店库存情况
                    "iSaved INTEGER NOT NULL DEFAULT 0," +          //是否保存的历史数据 1是 0否
                    "iAddSelected INTEGER NOT NULL DEFAULT 1," +  //补充是否选择
                    "sNeedAddModels TEXT" +           //补充货源集合
                    ");");

            db.execSQL("Create table "
                    + TABLE_PROMOTERINFO + " (" +  //促销员信息表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sStoreID TEXT," +           //门店ID
                    "sPromoterId TEXT," +     //促销员ID
                    "sPromoterName TEXT," +   //促销员名字
                    "iInpost INTEGER NOT NULL DEFAULT -1," +      //在岗情况
                    "iImage INTEGER NOT NULL DEFAULT -1," +        //形象
                    "iStatus INTEGER NOT NULL DEFAULT -1," +       //状态
                    "sBadReason TEXT," +           //不好原因
                    "iCheck INTEGER NOT NULL DEFAULT -1," +           //考勤
                    "iTemporary INTEGER NOT NULL DEFAULT -1," +       //临时情况
                    "sTempName TEXT," +           //临时促销员名字
                    "sTempTel TEXT," +           //临时促销员电话
                    "sNotPostReason TEXT," +     //不在岗原因
                    "sProblem TEXT," +          //促销员问题
                    "iSaved INTEGER NOT NULL DEFAULT 0," +          //是否保存的历史数据 1是 0否
                    "iLast INTEGER NOT NULL DEFAULT 0," +          //是否保存的上次同步前促销员
                    "sPhoto BLOB" +          //照片
                    ");");

            db.execSQL("Create table "
                    + TABLE_COMPETEINFO + " (" +  //督导门店销量表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sStoreID TEXT," +          //门店ID
                    "sBrandID TEXT," +    //品牌ID
                    "sBrandName TEXT," + //品牌名字
                    "sModelID TEXT," +      //型号ID
                    "sModelName TEXT," +    //型号名字
                    "iPrice INTEGER," +      //价格
                    "iSellcount INTEGER," +      //销量
                    "sDataIDs TEXT," +           //数据ID集合（活动或者功能）
                    "sDataNames TEXT," +         //数据名字集合（活动或者功能）
                    "sOthers TEXT," +           //其他（活动或者功能）
                    "sPhoto BLOB," +           //照片
                    "iSaved INTEGER NOT NULL DEFAULT 0," +          //是否保存的历史数据 1是 0否
                    "iType TEXT" +           //数据类型( 1=竞品价格  2==新品功能  3==竞品活动)
                    ");");
            
            db.execSQL("Create table "
                    + TABLE_COMPETESELECT + " (" +  //督导门店销量表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "sStoreID TEXT," +          //门店ID
                    "iPriceSelected INTEGER NOT NULL DEFAULT 1," +  //竞品价格是否选择
                    "iNewSelected INTEGER NOT NULL DEFAULT 1," +  //新品功能是否选择
                    "iSaved INTEGER NOT NULL DEFAULT 0," +          //是否保存的历史数据 1是 0否
                    "iActivitySelected INTEGER NOT NULL DEFAULT 1" +  //竞品活动是否选择
                    ");");

            db.execSQL("Create table "
                    + TABLE_VISITSTATUS + " (" +  //拜访标识表
                    "_id INTEGER PRIMARY KEY," + //主键ID
                    "iVisitId INTEGER," + //拜访任务ID
                    "iStatus_shape INTEGER," +    //出样状态数据
                    "iStatus_booth INTEGER," +    //展台形状状态数据
                    "iStatus_sales INTEGER," +  //销量状态数据
                    "iStatus_posm INTEGER," +   //POSM状态数据
                    "iStatus_compete INTEGER," +  //竞品状态数据
                    "iStatus_promoter INTEGER," + //促销员任务状态数据
                    "iStatus_task INTEGER" +      //特殊任务状态数据
                    ");");

            TestData.insertModelsData(db);
            TestData.insertSalesTasksData(db);
            TestData.insertSupervisorVisitTasksData(db);
            TestData.insertDataDictionaryData(db);
            TestData.insertSupervisorPromoterData(db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            if (DATABASE_VERSION != oldVersion) {
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_SIGNININFO);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_MODELLIST);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDS);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_SPECIALTASKS);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_REPORTEDSALES);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_SUPERVISORVISITTASK);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_SUPERVISOR_STORESAMPLE);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_DATA_DICTIONARY);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_DATA_PROJECTS);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_SUPERVISOR_STOREBOOTH);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_SUPERVISOR_STOREPOSM);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_SUPERVISOR_STORESALES);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROMOTERINFO);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMPETEINFO);
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_VISITSTATUS);
                onCreate(db);
            }
        }
    }

    static class SqlArguments {
        public final String table;
        public final String where;
        public final String[] args;

        SqlArguments(Uri url, String where, String[] args) {
            if (url.getPathSegments().size() == 1) {
                this.table = url.getPathSegments().get(0);
                this.where = where;
                this.args = args;
            } else if (url.getPathSegments().size() != 2) {
                throw new IllegalArgumentException("Invalid URI: " + url);
            } else if (!TextUtils.isEmpty(where)) {
                throw new UnsupportedOperationException("WHERE clause not supported: " + url);
            } else {
                this.table = url.getPathSegments().get(0);
                this.where = "_id=" + ContentUris.parseId(url);
                this.args = null;
            }
        }

        SqlArguments(Uri url) {
            if (url.getPathSegments().size() == 1) {
                table = url.getPathSegments().get(0);
                where = null;
                args = null;
            } else {
                throw new IllegalArgumentException("Invalid URI: " + url);
            }
        }
    }
}
